package com.star.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.star.entity.User;
import com.star.result.Result;
import com.star.result.ResultCodeEnum;
import com.star.service.SendMailService;
import com.star.service.UserService;
import com.star.utils.AutoCodeUtils;
import com.star.utils.CustomChatGpt;
import com.star.utils.UserAutomaticUtil;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpHost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Author star
 * @Date 2023/3/28 23:10
 * @PackageName:com.star.controller
 * @ClassName: UserController
 * @Description: TODO
 * @Version 1.0
 */
@Api(tags = "用户登录接口")
@RestController
@RequestMapping("/user")
public class UserController {

    //线程安全    public static volatile Integer autoCode;
    public static volatile Integer autoCode;

    public static volatile String cell_phone;

    @Autowired
    private SendMailService sendMailService;


    @Autowired
    public UserService userService;

    @ApiOperation("手机验证码")
    @GetMapping("/code/{phone}")
    public void phoneVerify(@PathVariable String phone) {
        //生成验证码
        //生成6位随机数
        autoCode = Integer.valueOf(AutoCodeUtils.generateCode(6));
        cell_phone = phone;
        System.out.println(phone + ":" + autoCode);
        //根据手机号发送验证码
        AutoCodeUtils.sendCode(autoCode,phone);
        //3分钟后自动清除验证码 用lambda表达式
        new Thread(() -> {
            try {
                Thread.sleep(1000*60*3);
                autoCode = null;
                cell_phone = null;
                System.out.println("验证码已过期");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }


    @ApiOperation("邮箱验证码")
    @GetMapping("/emailCode/{email}")
    public void emailVerify(@PathVariable String email) {
        //生成验证码
        //生成6位随机数
        autoCode = Integer.valueOf(AutoCodeUtils.generateCode(6));
        //假装邮箱是手机号
        cell_phone = email;
        System.out.println(email + ":" + autoCode);
        //根据邮箱发送验证码
        sendMailService.sendmail(autoCode,email);
        //3分钟后自动清除验证码 用lambda表达式
        new Thread(() -> {
            try {
                Thread.sleep(1000*60*3);
                autoCode = null;
                cell_phone = null;
                System.out.println("验证码已过期");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    @ApiOperation("手机验证码登录")
    @PostMapping("/codeLogin")
    public Result codeLogin(String phone, Integer code, HttpSession session) {
        if (cell_phone.equals(phone) && autoCode.equals(code)) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            //根据手机号查询用户
            User user = userService.getOne(wrapper);
            //如果用户不存在,则自动注册
            if (user == null) {
                //自动注册
                Result<User> result = autoRegister(phone, code);
                //注册成功则返回200
                if (result.getCode() == 200) {
                    //保存用户信息到session
                    session.setAttribute("user", result.getData().getUsername());
                    return Result.build(result.getData(), 200, "注册成功");
                }
            }
            //保存用户信息到session
            session.setAttribute("user", user.getUsername());
            //返回用户信息
            return Result.ok(user);
        }
        //返回验证码错误
        return Result.build(null, ResultCodeEnum.AUTO_CODE);
    }

    @ApiOperation("邮箱验证码登录")
    @PostMapping("/emailCodeLogin")
    public Result emailCodeLogin(String email, Integer code, HttpSession session) {
        if (cell_phone.equals(email) && autoCode.equals(code)) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("email", email);
            //根据邮箱号查询用户
            User user = userService.getOne(wrapper);
            //如果用户不存在,则自动注册
            if (user == null) {
                //自动注册
               Result<User> result = emailRegister(email, code);
                //注册成功则返回200
                if (result.getCode() == 200) {
                    //保存用户信息到session
                    session.setAttribute("user", result.getData().getUsername());
                    return Result.build(result.getData(), 200, "注册成功");
                }
            }
            //保存用户信息到session
            session.setAttribute("user", user.getUsername());
            //返回用户信息
            return Result.ok(user);
        }
        //返回验证码错误
        return Result.build(null, ResultCodeEnum.AUTO_CODE);

    }

    @ApiOperation("根据名称获取用户信息")
    @GetMapping("/getByName")
    public User getByName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //根据用户名查询用户
        wrapper.eq("username", username);
        User user = userService.getOne(wrapper);
        return user;
    }

    @ApiOperation("获取指定用户信息")
    @GetMapping("/{id}")
    public User getByIdUser(@PathVariable int id) {
        User user = userService.getById(id);
        return user;
    }

    @ApiOperation("登录")
    @GetMapping("/login")
    public Result login(String username, String password, HttpSession session) {
        User user1 = userService.UserLogin(username);
        if (user1 == null) {
            return Result.build(null, ResultCodeEnum.LOGIN_MOBLE_ERROR);
        }
        if (password.equals(user1.getPassword())) {

            session.setAttribute("user", user1.getUsername());

            return Result.ok(user1);
        }
        return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
    }


    @ApiOperation("使用验证码注册")
    @PostMapping("/autoRegister")
    public Result<User> autoRegister(String phone, Integer code) {
        User user = null;
        if (cell_phone.equals(phone) && autoCode.equals(code)) {
            //自动生成默认用户,后续可更改
            user = UserAutomaticUtil.autoUser(phone);
            System.out.println(user);
            boolean save = userService.save(user);
            if (save) {
                return Result.ok(user);
            }
        }
        return Result.build(null, ResultCodeEnum.AUTO_CODE);
    }


    public Result<User> emailRegister(String email, Integer code) {
        User user = null;
        if (cell_phone.equals(email) && autoCode.equals(code)) {
            //自动生成默认用户,后续可更改
            user = UserAutomaticUtil.emailAutoUser(email);
            System.out.println(user);
            boolean save = userService.save(user);
            if (save) {
                return Result.ok(user);
            }
        }
        return Result.build(null, ResultCodeEnum.AUTO_CODE);
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public Result register(User user) {
        boolean save = userService.save(user);
        if (save) {
            return Result.ok(user);
        }
        return Result.fail();
    }


    @ApiOperation("得到本地session记录用户")
    @GetMapping("/getUsername")
    public String getUsername(HttpSession session) {
        String username = (String) session.getAttribute("user");
        return username;
    }

    @ApiOperation("发送邮箱")
    @GetMapping("/sendMail")
    public void sendMail(String message){
        sendMailService.sendMail(message);
    }

    @ApiOperation("chatgpt")
    @GetMapping("/chatgpt")
    public Result ChatGPT(String message){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String apiKey = "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";
        CustomChatGpt customChatGpt = new CustomChatGpt(apiKey);
        //设置请求超时时间
        customChatGpt.setResponseTimeout(20000);
        String answer = customChatGpt.getAnswer(httpClient, message);
        return Result.ok(answer);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public Result logout(HttpSession session) {
        session.removeAttribute("user");
        return Result.ok();
    }

}
